package com.jprocms.module.cms.controller.directive;

import com.jprocms.module.cms.controller.admin.content.relatevo.ContentRelateReqVO;
import com.jprocms.module.cms.dal.dataobject.content.ContentDO;
import com.jprocms.module.cms.service.content.ContentRelateService;
import com.jprocms.module.cms.util.Freemarkers;
import com.jprocms.module.cms.web.Directives;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import static com.jprocms.module.cms.web.Directives.getLong;


/**
 * 相关内容列表 自定义标签
 *
 * @author jprocms
 */
public class ContentRelateListDirective implements TemplateDirectiveModel {
    /**
     * 内容id
     */
    public static final String CONTENT_ID = "contentId";

    @SuppressWarnings("unchecked")
    @Override
    public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body)
            throws TemplateException, IOException {
        Freemarkers.requireLoopVars(loopVars);
        Freemarkers.requireBody(body);
        ContentRelateReqVO reqVO = new ContentRelateReqVO();
        reqVO.setContentId(getLong(params, CONTENT_ID));
        reqVO.setCount(Directives.getCount(params));
        List<ContentDO> relateContents = contentRelateService.getContentRelateListFront(reqVO);
        loopVars[0] = env.getObjectWrapper().wrap(relateContents);
        body.render(env.getOut());
    }

    private ContentRelateService contentRelateService;

    public ContentRelateListDirective(ContentRelateService contentRelateService) {
        this.contentRelateService = contentRelateService;
    }

}
